<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {
	
	
	function  __construct() 
	{
        parent::__construct();
		$this->load->library('session');	
		$this->load->library('form_validation');
		$this->load->model('Login_model');
	}
	
	function index()
	{
		$this->login();
	}
	
	
	function login()
	{
		if (is_login() == TRUE){
			redirect(base_url());
		}
		
		$data['username'] = $this->input->post('username');
		$data['password'] = $this->input->post('password');
		$data['message'] = '';
		
		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('username', 'Username', 'callback_usercheck');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
		$this->form_validation->set_message('required', '%s Tidak boleh kosong !!');
		
		if ($this->form_validation->run() == FALSE){		
			
			$this->load->view('login_form', $data);
			
			
		}else{												
			
			$row = $this->Login_model->get_user($data['username'], $data['password']);
			
			if ($row->num_rows() > 0){ 										
				
				$token = md5($row->row()->intid_user . time());
				$this->Login_model->set_token($row->row()->intid_user, $token);
				$this->session->set_userdata('token', $token);
				
				
				$log_as = $this->Login_model->get_logged_as($row->row()->intid_user);
				$this->session->set_userdata('logged_as', $log_as);
				$this->session->set_userdata('userid', $row->row()->intid_user);
				$this->session->set_userdata('username', $this->input->post('username'));
				$this->session->set_userdata('privilege', $row->row()->intid_privilege);
				$this->session->set_userdata('is_logged_in', true);
				
				$this->load->view('admin_views/home');
				//redirect(base_url());
				
			}else{															
				$data['message'] = 'Akses ditolak!';
				$this->load->view('login_form', $data);
			}
			
		}
	}
	
	function logout()
	{
		$this->session->sess_destroy();
		redirect('login','refresh');
	}

}